package com.quyunshuo.module.home.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

class MyLineProgressView2(
    context: Context,
    attrs: AttributeSet? = null,
) : View(context, attrs) {

    // 画笔
    private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND // 两端为圆角
    }

    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND // 进度条两端为圆角
    }
    // 线条高度
    private var lineHeight: Float = 15f

    // 默认颜色值
    private var defaultBackgroundColor = Color.LTGRAY
    private var defaultProgressColor = Color.BLUE

    init {
        // 设置画笔
        bgPaint.strokeWidth = lineHeight
        bgPaint.color = defaultBackgroundColor

        progressPaint.strokeWidth = lineHeight
        progressPaint.color = defaultProgressColor
    }

    private var progress:Float = 90f
        set(value) {
            field = value.coerceIn(0f, 100f) // 限制在0-100范围
            invalidate() // 更新UI
        }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val mode = MeasureSpec.getMode(heightMeasureSpec)
        var size = MeasureSpec.getSize(heightMeasureSpec)

        if (mode!=MeasureSpec.EXACTLY) {
            val heightSize = (lineHeight+paddingTop+paddingBottom).toInt()
            size = heightSize.coerceAtMost(size)
        }

        val width =  MeasureSpec.getSize(widthMeasureSpec)
        setMeasuredDimension(width,size)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 计算线条Y坐标位置（垂直居中）
        val centerY = height / 2f

        // 可用宽度（减去两端的padding）
        val usableWidth = width - paddingStart - paddingEnd //为什么要减去呢？因为width包含了padding
        /*
        public void drawLine(float startX, float startY, float stopX, float stopY,
            @NonNull Paint paint) {
         */
        canvas.drawLine(paddingStart.toFloat(),centerY,(usableWidth+paddingStart).toFloat(),centerY,bgPaint)

        if (progress>0){
            //这样写不太对吧，，，，宽度如何约束呢？？？
//            canvas.drawLine(paddingStart.toFloat(),centerY,(progress+paddingStart).toFloat(),centerY,progressPaint)

            // 计算进度线长度
            val progressWidth = usableWidth * progress / 100f //化成100%

            canvas.drawLine(paddingStart.toFloat(),centerY,(progressWidth+paddingStart).toFloat(),centerY,progressPaint)

        }
    }
}